package com.caigou.security.utils;



import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by echisan on 2018/6/23
 */
@Component
@Data
public class JwtTokenUtils {

    //无需验证路径
    //public static final String PREFIX = "/es,/user/sendSmsCode,/user/register,/user/forgot/password,/dic,/es,/esItem";


    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";

    public static final int TOKEN_LIFE_TIME = 6 ; //token存放在redis中的存活时间

    private static final String SECRET = "jwtsecretdemo";
    private static final String ISS = "echisan";

    // 角色的key
    private static final String ROLE_CLAIMS = "rol";
    private static final String AUTHORITY_CLAIMS = "authority";

    //redisRSA权限校验公钥
    public static final String PUBLIC_KYE = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrXedWNr1qrD3B3BUbzpjuk-bqAxVszBBHtqiPfZGEtNuYlYa2DV-AbggVZrKxGgRDkjFKxjCN9EvTLM5SjCbRqgf39djhyFw29CuxyqI77jIbnkKU8VqiTblo6wqcjx_YjoTAgYab_f3d11mZw_tc-E3SPPwaEyo2vqckxi_ZbwIDAQAB";

    //redisRSA权限校验私钥
    public static final String PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKtd51Y2vWqsPcHcFRvOmO6T5uoDFWzMEEe2qI99kYS025iVhrYNX4BuCBVmsrEaBEOSMUrGMI30S9MszlKMJtGqB_f12OHIXDb0K7HKojvuMhueQpTxWqJNuWjrCpyPH9iOhMCBhpv9_d3XWZnD-1z4TdI8_BoTKja-pyTGL9lvAgMBAAECgYBG0yKfYTRb-B_2FU2sFnDiecJACVI7iwNXgEieNVmFLXJs16-7Yj-MRu2UWsOTqpsEilFRBCRhJwyHlMcZGs-XvZux5MUWqflL2vvk_uJ82gLKklvsl2BTC2JepsIbxyZELADZSpmwIHXTY2QYZ-b1UNoJgEYW27NFUI-5uHEhMQJBAOqr2S_JjwCA0y8MZNEwZC9YtDh0bJZ44hw0WJXd8xe6A__GEVLtQ-DMg35crZbtElfsMWy2lukgH_iPmPB6MJMCQQC68SKk86yKMlM6OilkXRI0_qy0BSywusAaB3k7enrDw7UyBGeCC5-VfYhOv2CKl7jP_A9yzSEBE2-szyVhWuk1AkButaACwW4raJs4yPoPDmtVQt3S_Gn2GxVhBPj9yvXSLbmRQxoNK04okZM_W-2xFCrhO9adWQ6c8MDkfKpEWQDtAkEAqD549Yewkzezm8XYltEEn9lMyT-W9v88ALEVNKiIcENkgb1hArM_TqUJ1gV694CQ_e5WYPWobHV3nklX1QSiuQJAbay1Mk8GVTH_1qI5jJCEYkFhVTPVEPBmV-zwuhljz1R54Y1mkavWAAdX5zU9p9yQF8I44tiUbtRdbFmiY5quvQ";


    // Jwt中token的过期时间是3600秒，既是1个小时
    private static final long EXPIRATION = 72000000L;

    // Jwt中token的过期时间，选择了记住我之后的过期时间为7天
    private static final long EXPIRATION_REMEMBER = 72000000;

    // 创建token
    public static String createToken(String username,String userId,List<String> privileges, boolean isRememberMe) {
        long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION;
        HashMap<String, Object> map = new HashMap<>();
        //map.put(ROLE_CLAIMS, role);
        map.put(AUTHORITY_CLAIMS, privileges);
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .setClaims(map)
                .setIssuer(ISS)
                .setId(userId)
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .compact();
    }

    // 从token中获取用户名
    public static String getUsername(String token){
        return getTokenBody(token).getSubject();
    }

    // 从token中获取用户id
    public static String getUserId(String token){
        return getTokenBody(token).getId();
    }

    // 获取用户角色
    public static String getUserRole(String token){
        return (String) getTokenBody(token).get(ROLE_CLAIMS);
    }

    //获取用户权限
    public static List<String> getUserAuthorities(String token){
        return (List<String>) getTokenBody(token).get(AUTHORITY_CLAIMS);
    }

    // 是否已过期
    public static boolean isExpiration(String token) {
        try {
            return getTokenBody(token).getExpiration().before(new Date());
        } catch (ExpiredJwtException e) {
            return true;
        }
    }

    private static Claims getTokenBody(String token){
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    }
}
